/***
 * @creater:wjiban
 * @create_time:20-10-18 16:10:17
 * @last_modify:wjiban
 * @modify_time:20-10-23 23:37:3
 * @line_count:116
 **/

import Mock from "mockjs";

var str = Mock.mock({
  "name|1-10": "zk", //1-10次重复
  "home|3": "china" //3次重复
});
console.log(str);

var num = Mock.mock({
  age: 22,
  "int|1-100": 100, //1-100随机
  "floor1|1-100.1-5": 1, //整数部分1-100，小数1-5位
  "floor2|23.1-3": 1, //整数23，小数1-3位
  "floor3|123.3": 1 //整数123，小数3位
});
console.log(num);

// 自定义数据进行供应请求
let { newList } = Mock.mock({
  "newList|55-65": [
    {
      id: "@increment()",
      title: "@ctitle()",
      content: "@cparagraph(8,15)",
      add_time: "@date('yyyy-MM-dd H:m:s')",
      img_url: "@image('100x100', '#c63939', '#ffb3b3', 'png', 'mockjs')"
    }
  ]
});
console.log(newList);

// 获取url地址参数
const getQuery = (url, name) => {
  // console.log(url, name);
  const index = url.indexOf("?");
  if (index !== -1) {
    const queryStrArr = url.substr(index + 1).split("&");
    for (let i = 0; i < queryStrArr.length; i++) {
      const item = queryStrArr[i].split("=");
      // console.log(item);
      if (item[0] === name) return item[1];
    }
  }
  // console.log(index);
  return null;
};

//   **************************************示例************************************************
//   定义get请求   对象
// Mock.mock("/api/get/news", "get", {
//   status: 200,
//   msg: "GET数据成功"
// });

// 定义数据过去新闻数据信息
//正则转义url    定义请求数据接口
Mock.mock(/\/api\/get\/new/, "get", options => {
  // 获取传递的参数pageIndex、pageSize
  const pageIndex = getQuery(options.url, "pageIndex");
  const pageSize = getQuery(options.url, "pageSize");
  
  // 截取数组的起始位置
  const start = (pageIndex - 1) * pageSize;
   // 截取数组的终点位置
  const end = pageIndex * pageSize;
  // 计算总页数
  const totalPage = Math.ceil(newList.length/pageSize);//Math.ceil()向上取整  floor向下
  // 数组截取，确保数据不够截取时，返回一空数组；
  const list = pageIndex>totalPage?[]:newList.slice(start,end);
  // console.log(pageIndex);//1
  return {
    status: 200,
    msg: "数据请求成功！",
    list: list,
    total: newList.length
  };
});

//   定义port请求  函数返回对象    定义添加数据接口
Mock.mock("/api/add/news", "post", (options) => {
  const body = JSON.parse(options.body);
  // console.log(body);
  newList.push(
    Mock.mock({
      id: "@increment()",
      title: body.title,
      content: body.content,
      add_time: "@date('yyyy-MM-dd H:m:s')",
      img_url: "@image('100x100', '#c63939', '#ffb3b3', 'png', 'mockjs')"
    })
  )
  return {
    status: 200,
    msg: "数据添加成功！",
    list:newList,
    total:newList.length
  };
});


// 定义移除数据接口
Mock.mock("/api/delete/news", "post", (options) => {
  const body = JSON.parse(options.body);
  // console.log(body);
  const index = newList.findIndex(item=>{
    return item.id === body.id
  })
  console.log(index)
  newList.splice(index,1);//使用split截取移除
  return {
    status: 200,
    msg: "数据移除成功！",
    list:newList,
    total:newList.length
  };
});